package com.cddata;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.cddata.util.DBOperation;


@SuppressWarnings("serial")
public class FileUpload extends JPanel implements ActionListener{
	public FileUpload(){
		display();
	}

	private void display() {
		JPanel uploadPanel = new JPanel();
		uploadPanel.setLayout(new BoxLayout(uploadPanel , BoxLayout.Y_AXIS));
		uploadPanel.add(DBOperation.getHelperBean().createHeaderPanel("Upload File...", null));
		uploadPanel.add(createFilePanel());
		uploadPanel.add(createButtonPanel());
		add(uploadPanel);
		setVisible(true);
	}

	private JPanel createFilePanel () {
		JPanel filePanel = new JPanel();
		filePanel.setName("filePanel");

		fileName = new JTextField(15);
		fileName.setEditable(false);
		JButton fileButton = new JButton("Choose File...");
		fileButton.addActionListener(this);
	
		filePanel.add( new JLabel("File:"));
		filePanel.add(fileName);
		filePanel.add(fileButton);

		return filePanel;
	}

	private JPanel createButtonPanel () {
		JPanel buttonPanel = new JPanel();
		JButton uploadButton = new JButton("Upload...");
		uploadButton.addActionListener(this);
		JButton resetButton = new JButton("Reset...");
		resetButton.addActionListener(this);
		buttonPanel.add(uploadButton);
		buttonPanel.add(resetButton);
		return buttonPanel;
	}

	public void actionPerformed( ActionEvent ae ) {
		String action = ae.getActionCommand();
		if( "Choose File...".equalsIgnoreCase( action ) ) {
			JFileChooser fileChooser = new JFileChooser();
			try{
				fileChooser.setCurrentDirectory(new File("./files").getCanonicalFile() );
			}catch (Exception e) {
				e.printStackTrace();
			}
			int option = fileChooser.showOpenDialog(this);
			if( option == JFileChooser.APPROVE_OPTION ) {
				file = fileChooser.getSelectedFile();
				fileName.setText(file.getName()); 
			} else {
				return;
			}
		} else if( "Upload...".equalsIgnoreCase(action) ) {
			if( file == null ) {
				JOptionPane.showMessageDialog(this, "No File Selected !... ");
				return;
			} else {
				FileDataThread threadDemo = new FileDataThread(file, fileName.getText());
				Thread t1 = threadDemo;
				t1.start();
			}

		} else if( "Reset...".equalsIgnoreCase(action)) {
			file = null;
			fileName.setText("");
		} else {

		}
	}

	JTextField fileName = null;
	File file = null;
}
